package ndquangr.intern.ringtonemaker;


import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.TypedValue;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class EditAudioActivity extends Activity {
	/** Global variables */
	private Context m_context;
	private ContentResolver mCr;
	private File rootFolder;

	
	private Bitmap m_graph;
	private int displayWidth, displayHeight;	
	private int startTime, endTime;
	private float graph_realPos, start_realPos, end_realPos;
	private int img_width, img_height;
	
	private int GRAPH_HEIGHT;
	private int DEFAULT_SELECTION_WIDTH = 100;
	
	/** Control variables */
	private ImageView img_graph;
	private ImageView img_selection;
	private ImageView img_pointer;
	private ImageView img_selection_start;
	private ImageView img_selection_end;
	private ImageButton btn_play;
	//private ImageView btn_end;
	//private ImageView btn_apply;
	private ImageView btn_save;
	//private ImageView btn_close;	
	private TextView tv_songtitle;
	private TextView tv_songtime;
	private CheckBox cb_alarm, cb_notification, cb_ringtone, cb_alarmDefault, cb_notificationDefault, cb_ringtoneDefault;
	private Drawable slider;
	private ProgressDialog progDailog;
	private EditText edt_startTime;
	private EditText edt_endTime;
	
	short [] data; // Data cheap read for every 10ms
	WavIO waveFile;
	NativeMP3Decoder mp3Decoder;
	
	//public static int MAX_SAMPLES = 50000;
	private MediaPlayer mp = new MediaPlayer();
	private String filePath;
	private String songtitle;
	private int fileDuration;
	private FILE_TYPE filetype;
	private boolean START_TEXT_CHANGED_BY_SLIDER;
	private boolean END_TEXT_CHANGED_BY_SLIDER;
	private boolean IS_MEDIA_PAUSED, IS_MEDIA_STARTED;
	
	// Initialization	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.edit_audio_layout);
        m_context = this;
        mCr = getContentResolver();
        rootFolder = new File(Environment.getExternalStorageDirectory(),Constants.ROOT_FOLDER);// "My tones");
        if (!rootFolder.exists()) {
        	rootFolder.mkdirs();
        }
        
		// Get information from intent
        Bundle extras = getIntent().getExtras();
		if (extras != null) {			
			
			// Get specific songs base on tag
			filePath = extras.getString("uri");	
			
			// Set up media player
			initializeMediaPlayer(filePath);
			if (filePath == null) {
				return;
			} 
			String [] tempstr = filePath.split("/");
			songtitle = tempstr[tempstr.length - 1];
			// If the file type is mp3 then it is needed to decode
			if (filePath.toLowerCase().endsWith(".mp3")) {
				// Show progress dialog			
				progDailog = ProgressDialog.show(m_context,
						"Decoding Mp3", "Please wait....",
						true);
				new Thread() {
					public void run() { 
						// Decode MP3 file	
						filetype = FILE_TYPE.MP3;
						mp3Decoder = new NativeMP3Decoder(filePath);
						if (mp3Decoder.getHandle() != -1) {			
							filePath = mp3Decoder.saveMp3ToTempFile(fileDuration, rootFolder.getAbsolutePath());
						}
						if (filePath != null) {
							initializeMediaPlayer(filePath);
						} 
						progDailog.dismiss();
						Message msg = new Message();
			        	msg.obj = filePath;
			        	msg.what = 2;
			        	msg.setTarget(handler);			        	
			        	msg.sendToTarget();
					} 
					
				}.start();				
			} else if (filePath.toLowerCase().endsWith(".wav")) {
				filetype = FILE_TYPE.WAV;
				processWAV();
			}		
			
		}		        
	}

	private void processWAV() {
		// Show progress dialog
		progDailog = ProgressDialog.show(m_context,
				"Generating audio amplitude graph", "Please wait....",
				true);
		
		new Thread() {
			public void run() {
				try{		
					if (filePath != null && filePath.endsWith(".wav")) {
						data = new short [fileDuration/10];
						readPCM(filePath);
					}
					/*
					if (filePath != null && filePath.endsWith(".wav")) {
						filetype = FILE_TYPE.WAV;
						readPCM(filePath);		
						
					} else {
						filetype = FILE_TYPE.MP3;
						readMP3(filePath);
					}	*/					
				} catch (Exception e) { 
					e.printStackTrace();
				}
				Message msg = new Message();
				msg.what = 0;
				handler.sendMessage(msg);
				progDailog.dismiss(); 
				}
			}.start();
	}

	String newFileNameFromDialog;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {			
			if (msg.what == 0) { // Draw graph
				setContentView(R.layout.edit_audio_layout);		
				// Get global values
			    Display display = ((WindowManager)
		        getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
	
			    displayWidth = display.getWidth();             
			    displayHeight = display.getHeight();
			    graph_realPos = 0; 
			    start_realPos = 0; 
			    end_realPos = DEFAULT_SELECTION_WIDTH;
			    GRAPH_HEIGHT = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, getResources().getDisplayMetrics());
			    
			    // Get all control instances
				getControlInstances();
				
				// Add action listener for controls
		        addActionListener(); 
				
				// Initialize view for graph of audio data
		        initializeGraph();
			} else if (msg.what == 1) { // save file
				// Save file
				newFileNameFromDialog = msg.obj.toString();
				
				// Show progress dialog			
				progDailog = ProgressDialog.show(m_context,
						"Saving audio file", "Please wait....",
						true);
				
				// Start a thread to save to a new file			
				new Thread() {
					public void run() {
						String newFilePath;
						if (newFileNameFromDialog == null || newFileNameFromDialog == "") {
							newFileNameFromDialog = "my ringtone";
						}
						
			            newFilePath = rootFolder.getAbsolutePath() +"/" + newFileNameFromDialog + ".wav";
			            boolean fileSaveResult = false;
			            /*
						if (filetype.equals(FILE_TYPE.WAV)) {
							// Save to new file							 
							fileSaveResult = waveFile.save(startTime, endTime, newFilePath);
							
						} else if (filetype.equals(FILE_TYPE.MP3)) {
							//fileSaveResult = mp3Decoder.saveMP3data(start_realPos*100, end_realPos*100, fileDuration, newFilePath);
							fileSaveResult = waveFile.save(start_realPos*100, end_realPos*100, newFilePath);							
						}
						*/
			            fileSaveResult = waveFile.save(startTime, endTime + 1, newFilePath);
						// Add metadata to new file
						if (fileSaveResult) {
							boolean isAlarm, isNotification, isRingtone;
							boolean isAlarmDefault, isNotificationDefault, isRingtoneDefault;
							isAlarm = cb_alarm.isChecked();
							isNotification = cb_notification.isChecked();
							isRingtone = cb_ringtone.isChecked();
							isAlarmDefault = cb_alarmDefault.isChecked();
							isNotificationDefault = cb_notificationDefault.isChecked();
							isRingtoneDefault = cb_ringtoneDefault.isChecked();
							
							ContentValues values = new ContentValues();
							values.put(MediaStore.MediaColumns.DATA, newFilePath);
							values.put(MediaStore.MediaColumns.TITLE, newFileNameFromDialog);
							values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/wav");
							//values.put(MediaStore.MediaColumns.SIZE, ((end_realPos - start_realPos)/10)*waveFile.getDataSize());
							values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name);
							values.put(MediaStore.Audio.Media.IS_RINGTONE, isRingtone);
							values.put(MediaStore.Audio.Media.IS_NOTIFICATION, isNotification);
							values.put(MediaStore.Audio.Media.IS_ALARM, isAlarm);
							values.put(MediaStore.Audio.Media.IS_MUSIC, false);
							values.put(MediaStore.Audio.Media.DURATION, endTime - startTime + 1);
							
							Uri uri = MediaStore.Audio.Media.getContentUriForPath(newFilePath);
						    mCr.delete(uri, MediaStore.MediaColumns.DATA + "=\"" + newFilePath + "\"", null);
						    mCr.insert(uri, values);
						    
						    
						    if (isRingtone && isRingtoneDefault) {
						    	// Set default ringtone
						    	RingtoneManager.setActualDefaultRingtoneUri(
						    			  m_context,
						    			  RingtoneManager.TYPE_RINGTONE,
						    			  uri
						    			);
						    } 
						    if (isNotification && isNotificationDefault) {
						    	// Set default notification
						    	RingtoneManager.setActualDefaultRingtoneUri(
						    			  m_context,
						    			  RingtoneManager.TYPE_NOTIFICATION,
						    			  uri
						    			);
						    } 
						    if (isAlarm && isAlarmDefault) {
						    	// Set default alarm
						    	RingtoneManager.setActualDefaultRingtoneUri(
						    			  m_context,
						    			  RingtoneManager.TYPE_ALARM,
						    			  uri
						    			);
						    } 
						}
						
						//handler.sendEmptyMessage(0);
						progDailog.dismiss(); 
						}
					}.start();						
			} else if (msg.what == 2) {
				if (msg.obj != null) {
					processWAV();
				}
			}
		}
	};
			
	private void initializeMediaPlayer(String fileName) {
		try {			
			mp.reset();		    
			mp.setDataSource(fileName);
		    mp.prepare();
		    fileDuration = mp.getDuration();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	    
	}
	
	/*
	 * Get view control instances
	 */
	private void getControlInstances() {
		img_graph = (ImageView) findViewById(R.id.img_audioEdit_graph);
		img_selection = (ImageView) findViewById(R.id.img_audioEdit_selection);
		img_selection_start = (ImageView) findViewById(R.id.img_audioEdit_startTime);
		img_selection_end = (ImageView) findViewById(R.id.img_audioEdit_endTime);
		img_pointer = (ImageView) findViewById(R.id.img_audioEdit_pointer);
		
		img_height = img_graph.getLayoutParams().height;	
		btn_play = (ImageButton) findViewById(R.id.btn_editAudio_play);
		btn_save = (ImageView) findViewById(R.id.btn_editAudio_save);
		edt_startTime = (EditText) findViewById(R.id.edt_audioEdit_startTime);
		edt_endTime = (EditText) findViewById(R.id.edt_audioEdit_endTime);
		tv_songtitle = (TextView) findViewById(R.id.tv_audioEdit_songTitle);
		tv_songtime = (TextView) findViewById(R.id.tv_audioEdit_totalTime);
		cb_alarm = (CheckBox) findViewById(R.id.cb_editAudio_isalarm);
		cb_ringtone = (CheckBox) findViewById(R.id.cb_editAudio_isringtone);
		cb_notification = (CheckBox) findViewById(R.id.cb_editAudio_isnotification);
		cb_alarmDefault = (CheckBox) findViewById(R.id.cb_editAudio_isalarmdefault);
		cb_ringtoneDefault = (CheckBox) findViewById(R.id.cb_editAudio_isringtonedefault);
		cb_notificationDefault = (CheckBox) findViewById(R.id.cb_editAudio_isnotificationdefault);
	}

	/*
	 * Add action listeners to controls
	 */
	private void addActionListener() {
		img_graph.setOnTouchListener(graphTouchEvent);
		img_selection_start.setOnTouchListener(startSelectionTouchEvent);
		img_selection_end.setOnTouchListener(endSelectionTouchEvent);
		btn_play.setOnClickListener(playButtonClickListener);
		btn_save.setOnClickListener(saveButtonClickListener);
		
		edt_startTime.setText("0");
		edt_endTime.setText("" + DEFAULT_SELECTION_WIDTH);
		edt_startTime.setOnEditorActionListener(startTimeValidate);
		edt_endTime.setOnEditorActionListener(endTimeValidate);
		
		tv_songtitle.setText("Title: " + songtitle);
		tv_songtime.setText("Total time: " + fileDuration + " ms");
		cb_alarm.setOnCheckedChangeListener(alarmCheckedListener);
		cb_ringtone.setOnCheckedChangeListener(ringtoneCheckedListener);
		cb_notification.setOnCheckedChangeListener(notificationCheckedListener);
	}

	/*
	 * Initialize audio data graph
	 */
	private void initializeGraph() {		
		m_graph = Bitmap.createBitmap(data.length/10, (int)Math.floor(GRAPH_HEIGHT), Bitmap.Config.ARGB_8888);
        createGraph(m_graph);

		//m_graph = BitmapFactory.decodeResource(getResources(), R.drawable.landscape);
		img_width = m_graph.getWidth();
		img_height = m_graph.getHeight();
		
		// Set up ImageView for graph
		img_graph.setImageBitmap(m_graph);
        
        slider = getResources().getDrawable(R.drawable.slider);
        
        img_selection_start.setImageDrawable(slider);
        img_selection_end.setImageDrawable(slider);
        img_selection_start.scrollTo((int) (-start_realPos + slider.getIntrinsicWidth()/2), 0);
        img_selection_end.scrollTo((int) (-end_realPos + slider.getIntrinsicWidth()/2), 0);
        
        drawSelectionRegion(start_realPos, end_realPos);
	}

	/*
	 * Generate graph (wave form) from audio data
	 */
	private void createGraph(Bitmap bitmap) {
		// TODO Auto-generated method stub
		Canvas canvas = new Canvas(bitmap);
		int y_scale = 50;
        
        final int color = Color.BLUE; 
        final Paint paint = new Paint();
        paint.setColor(color);
        
        float cur_point_x, cur_point_y;
        float next_point_x, next_point_y;


        int i = 1;
        next_point_x = 0;
        next_point_y = -data[0]/y_scale + GRAPH_HEIGHT/2;
        while(i<data.length) {
                cur_point_x = next_point_x;
                cur_point_y = next_point_y;
                next_point_x = i/10;
            next_point_y = -data[i]/y_scale + GRAPH_HEIGHT/2;
            canvas.drawLines(new float [] {cur_point_x, cur_point_y, next_point_x, 
                        next_point_y}, paint);
            i++;
        }

        int label_steps = fileDuration/15000;
        int sec, min;
        sec = 0; min = 0;
        String text;
        paint.setColor(Color.WHITE);
        //paint.setTextSize(10);
        for (i=1;i<label_steps;i++) {
        	sec += 15;
        	if (sec == 60) {
        		min++;
        		sec = 0;
        	}
        	text = "0" + min + ":" + sec;
        	if (sec == 0) {
        		text = text + "0";
        	}
        	canvas.drawText(text, i*150, 10, paint);
        }
        if (label_steps == 0) {
        	canvas.drawText("00:15", 150, 10, paint);
        }
	}

	/*
	 * Draw selection region
	 */
	private void drawSelectionRegion(float start, float end) {
		// TODO Auto-generated method stub
		if (end < 0 || start > displayWidth) {
			img_selection.setImageBitmap(null);
		} else {
			if (start < 0) {
				start = 0;
			} else if (end > displayWidth) {
				end = displayWidth;
			}
			Bitmap b = Bitmap.createBitmap(displayWidth, img_height, Bitmap.Config.ARGB_8888);
			Canvas canvas = new Canvas(b);
						
			Rect r = new Rect((int)start, 0, (int)end, img_height);
			Paint paint = new Paint();
			paint.setStyle(Paint.Style.FILL);
			paint.setColor(Color.CYAN);			
			paint.setAlpha(100);
			canvas.drawRect(r, paint);
			
			img_selection.setImageBitmap(b);
		}
		
		img_selection.refreshDrawableState();
		//img_selection.invalidate();
	}	

	/*
	 * Decode Mp3 files
	 */
	/*
	private void readMP3(String path) {
		// TODO Auto-generated method stub
		mp3Decoder = new NativeMP3Decoder(path);
		if (mp3Decoder.getHandle() != -1) {			
			mp3Decoder.readCheapSamples(data);
		}
	}
	 */
	/*
	 * Read wav file
	 */
	private void readPCM(String path) {
		// TODO Auto-generated method stub
		waveFile = new WavIO(path);
		if (!waveFile.read(data)){			
			// Inform user
		}
		
	}
	
	 /*
     * Action listeners for images
     */
    private int graph_real_scroll;
    private float graph_current_x;
	private float graph_scrollByX;
	
    // Action listener for touch event on graph
    private OnTouchListener graphTouchEvent = new OnTouchListener() {
            
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                    float curX;
                    
			        switch (event.getAction()) {
			            
			            case MotionEvent.ACTION_DOWN:
			                graph_current_x = event.getX();
			                break;
			            case MotionEvent.ACTION_MOVE:
			                curX = event.getX();
			                graph_scrollByX = (int) (graph_current_x - curX);
			                if ((graph_realPos + graph_scrollByX) < 0) {
			                    graph_real_scroll = (int) -graph_realPos;
			                    graph_realPos = 0;
			                }
			                else if ((graph_realPos + graph_scrollByX) > (img_width - displayWidth)) {
			                    graph_real_scroll = (int) (img_width - displayWidth - graph_realPos);
			                    graph_realPos = img_width - displayWidth;
			                } else {  
			                    graph_real_scroll = (int) graph_scrollByX;                          
			                    graph_realPos+= graph_scrollByX;
			                }
			
			                // Scroll graph and also the sliders
			                img_graph.scrollBy(graph_real_scroll, 0);
			                img_selection_start.scrollBy(graph_real_scroll, 0);
			                img_selection_end.scrollBy(graph_real_scroll, 0);
			                prepareRedrawSelectionRegion(false, false);
			                    
			                graph_current_x = curX;
			                break;
			                
			            case MotionEvent.ACTION_UP:
			                curX = event.getX();
			                graph_scrollByX = (int) (graph_current_x - curX);
			                if ((graph_realPos + graph_scrollByX) < 0) {
			                    graph_real_scroll = (int) -graph_realPos;
			                    graph_realPos = 0;
			                }
			                else if ((graph_realPos + graph_scrollByX) > (img_width - displayWidth)) {
			                    graph_real_scroll = (int) (img_width - displayWidth - graph_realPos);
			                    graph_realPos = img_width - displayWidth;
			                } else {  
			                    graph_real_scroll = (int) graph_scrollByX;                          
			                    graph_realPos+= graph_scrollByX;
			                }
			
			                // Scroll graph and also the sliders
			                img_graph.scrollBy(graph_real_scroll, 0);
			                img_selection_start.scrollBy(graph_real_scroll, 0);
			                img_selection_end.scrollBy(graph_real_scroll, 0);
			                prepareRedrawSelectionRegion(false, false);
			                break;
			        }
			
			        return true;
            }
    };
    
    private float start_current_x;
    private int start_scroll_by_x;
    private int start_real_scroll;
    // Action listener for touch event on graph
    private OnTouchListener startSelectionTouchEvent = new OnTouchListener() {
            
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                    float curX;
                    
			        switch (event.getAction()) {
			            
			            case MotionEvent.ACTION_DOWN:
			                start_current_x = event.getX();
			                break;
			            case MotionEvent.ACTION_MOVE:
			                curX = event.getX();
			                start_scroll_by_x = (int) (start_current_x - curX);
			                if ((start_realPos-start_scroll_by_x) < 0) {
			                	start_real_scroll = (int) start_realPos;
			                } else if ((end_realPos-start_scroll_by_x) > img_width) {
			                	start_real_scroll = (int) (end_realPos - img_width);
			                } else {
			                	start_real_scroll = start_scroll_by_x;
			                }
			                start_realPos -= start_real_scroll;
			                end_realPos -= start_real_scroll;
			                
			                // Scroll two sliders
			                img_selection_start.scrollBy(start_real_scroll, 0);
			                img_selection_end.scrollBy(start_real_scroll, 0);                
			                prepareRedrawSelectionRegion(true, true);
			                
			                start_current_x = curX;
			                break;
			                
			            case MotionEvent.ACTION_UP:
			            	curX = event.getX();
			                start_scroll_by_x = (int) (start_current_x - curX);
			                if ((start_realPos-start_scroll_by_x) < 0) {
			                	start_real_scroll = (int) start_realPos;
			                } else if ((end_realPos-start_scroll_by_x) > img_width) {
			                	start_real_scroll = (int) (end_realPos - img_width);
			                } else {
			                	start_real_scroll = start_scroll_by_x;
			                }
			                start_realPos -= start_real_scroll;
			                end_realPos -= start_real_scroll;
			                
			                // Scroll two sliders
			                img_selection_start.scrollBy(start_real_scroll, 0);
			                img_selection_end.scrollBy(start_real_scroll, 0);                
			                prepareRedrawSelectionRegion(true, true);
			                
			                break;
			        }
			
			        return true;
            }
    };
    
    private float end_current_x;
    private int end_scroll_by_x;
    private int end_real_scroll;
    // Action listener for touch event on graph
    private OnTouchListener endSelectionTouchEvent = new OnTouchListener() {
            
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                    float curX;
                    
			        switch (event.getAction()) {            
			            case MotionEvent.ACTION_DOWN:
			                end_current_x = event.getX();
			                break;
			            case MotionEvent.ACTION_MOVE:
			                curX = event.getX();
			                end_scroll_by_x = (int) (end_current_x - curX);
			                if ((end_realPos - end_scroll_by_x) > img_width) {
			                	end_real_scroll = (int) (end_realPos - img_width);
			                } else if ((end_realPos - end_scroll_by_x) < (start_realPos)) {
			                	end_real_scroll = (int) (end_realPos - start_realPos);
			                } else {
			                	end_real_scroll = end_scroll_by_x;
			                }
			                
			                end_realPos -= end_real_scroll;
			                
			                img_selection_end.scrollBy(end_real_scroll, 0);
			                prepareRedrawSelectionRegion(false, true);
			                end_current_x = curX;
			                break;
			                
			            case MotionEvent.ACTION_UP:
			            	curX = event.getX();
			                end_scroll_by_x = (int) (end_current_x - curX);
			                if ((end_realPos - end_scroll_by_x) > img_width) {
			                	end_real_scroll = (int) (end_realPos - img_width);
			                } else if ((end_realPos - end_scroll_by_x) < (start_realPos)) {
			                	end_real_scroll = (int) (end_realPos - start_realPos);
			                } else {
			                	end_real_scroll = end_scroll_by_x;
			                }
			                
			                end_realPos -= end_real_scroll;
			                
			                img_selection_end.scrollBy(end_real_scroll, 0);
			                prepareRedrawSelectionRegion(false, true);
			                
			                break;
			        }

			        return true;
            }
            
    };
	
	private OnClickListener playButtonClickListener = new OnClickListener() {		
		@Override
		public void onClick(View v) {
						
			if (!IS_MEDIA_STARTED) {
				mp.seekTo((int) (start_realPos*100));
				mp.start();
				startTime = mp.getCurrentPosition();
				IS_MEDIA_STARTED = true;
				btn_play.setImageResource(R.drawable.media_playback_pause);
				new Thread() {
					public void run() {
						while(mp != null && mp.isPlaying())
						{
							int position = mp.getCurrentPosition();
							if(position % 100 == 0) {
								Message msg = new Message();
					        	msg.obj = position;
					        	msg.what = 0;
					        	msg.setTarget(pointerDrawHandler);			        	
					        	msg.sendToTarget();
							}
							if (position/100 >= end_realPos) {
								mp.pause();
								IS_MEDIA_STARTED = false;
								IS_MEDIA_PAUSED = false;
								btn_play.setImageResource(R.drawable.media_playback_start);
								endTime = mp.getCurrentPosition();
							}
						}
					}}.start();
			} else {
				if (!IS_MEDIA_PAUSED) {
					mp.pause();
					IS_MEDIA_PAUSED = true;
					btn_play.setImageResource(R.drawable.media_playback_start);					
				} else {
					mp.start();
					IS_MEDIA_PAUSED = false;
					btn_play.setImageResource(R.drawable.media_playback_pause);
					new Thread() {
						public void run() {
							while(mp != null && mp.isPlaying())
							{
								int position = mp.getCurrentPosition();
								if(position % 100 == 0) {
									Message msg = new Message();
						        	msg.obj = position;
						        	msg.what = 0;
						        	msg.setTarget(pointerDrawHandler);			        	
						        	msg.sendToTarget();
								}
								if (position/100 >= end_realPos) {
									mp.pause();
									IS_MEDIA_STARTED = false;
									IS_MEDIA_PAUSED = false;
									btn_play.setImageResource(R.drawable.media_playback_start);
									endTime = mp.getCurrentPosition();
								}
							}
						}}.start();
				}
			}
			
			//handler.post(playingProgressCheck);
			
			
		}
	};
	
	private Handler pointerDrawHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {			
			if (msg.what == 0) { 
				int drawPosition = Integer.parseInt(msg.obj.toString());
				drawPointer((int) ((drawPosition-graph_realPos*100)/100));
			}
		}
	};
	
	/*
	 * Save audio file in specific start and end time to wav file
	 */
	private OnClickListener saveButtonClickListener = new OnClickListener() {
				
		@Override
		public void onClick(View v) {
			
			// Require user input new file name
			LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View dialogView = li.inflate(R.layout.get_filename_dialog, null);

			//Button okButton = (Button) dialogView.findViewById(R.id.btn_filenameDialog_ok);
			final EditText edtFileName = (EditText)dialogView.findViewById(R.id.edt_filenameDialog_filename);

			AlertDialog filenameDialog = new AlertDialog.Builder(m_context)
			    .setTitle("Enter new file name")
			    .setView(dialogView)
			    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
			        public void onClick(DialogInterface dialog, int whichButton) {
			        	String filename = edtFileName.getText().toString();
			        	Message msg = new Message();
			        	msg.obj = filename;
			        	msg.what = 1;
			        	msg.setTarget(handler);			        	
			        	msg.sendToTarget();
			        }
			    }).create();
			filenameDialog.show();
		}
	};
		
	private void prepareRedrawSelectionRegion(boolean start, boolean end) {
		//img_selection_start.getDrawingRect(start_rect);
		//img_selection_end.getDrawingRect(end_rect);
		//drawSelectionRegion(start_rect.left, end_rect.left);
		// Update text box
		if (start) {
			START_TEXT_CHANGED_BY_SLIDER = true;
			END_TEXT_CHANGED_BY_SLIDER = true;
			edt_startTime.setText("" + (int)start_realPos);
			edt_endTime.setText("" + (int)end_realPos);			
		} else if (end) {
			END_TEXT_CHANGED_BY_SLIDER = true;
			edt_endTime.setText("" + (int)end_realPos);
		}
		drawSelectionRegion(start_realPos - graph_realPos, end_realPos - graph_realPos);
	}
	
	private void drawPointer(int position) {
		// TODO Auto-generated method stub
		if(position < 0 || position > displayWidth) {
			img_pointer.setImageBitmap(null);
			
		} else {
			Bitmap b = Bitmap.createBitmap(displayWidth, img_height, Bitmap.Config.ARGB_8888);
			Canvas canvas = new Canvas(b);
			Paint paint = new Paint();
			paint.setStyle(Paint.Style.STROKE);
			paint.setColor(Color.YELLOW);			
			paint.setPathEffect(new DashPathEffect(new float[] {5,5}, 0));
			canvas.drawLine(position, 0, position, img_height, paint);
			img_pointer.setImageBitmap(b);
		}
	
		img_pointer.refreshDrawableState();
	}
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        	if (mp.isPlaying()) {
        		mp.release();
        		mp = null;
        	}
        	if (filetype.equals(FILE_TYPE.MP3)) {
        		File file = new File(filePath);
				file.delete();
        	}
            return super.onKeyDown(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);
    }
	
	private OnEditorActionListener startTimeValidate = new OnEditorActionListener() {		
		@Override
		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
			if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT) {

				// TODO Auto-generated method stub
				if(!START_TEXT_CHANGED_BY_SLIDER) {
					
					// Change slider
					try{
						int newValue = Integer.parseInt(edt_startTime.getText().toString());
						if (0<newValue && newValue > (fileDuration-100)) {
							edt_startTime.setText("" + start_realPos);
						} else {
							start_realPos = newValue;
							end_realPos = newValue + DEFAULT_SELECTION_WIDTH;
							edt_endTime.setText("" + (int)end_realPos);
							//img_graph.scrollTo((int) -start_realPos, 0);
							img_selection_start.scrollTo((int) -start_realPos + slider.getIntrinsicWidth()/2, 0);
							img_selection_end.scrollTo((int) -start_realPos-DEFAULT_SELECTION_WIDTH + slider.getIntrinsicWidth()/2, 0);
							drawSelectionRegion(start_realPos - graph_realPos, end_realPos - graph_realPos);
						}
					} catch (NumberFormatException e) {
						edt_startTime.setText("" + start_realPos);
						
					}
				} else {
					START_TEXT_CHANGED_BY_SLIDER = false;
				} 

            }
            return false;

		}
	};
	private OnEditorActionListener endTimeValidate= new OnEditorActionListener() {
		
		@Override
		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
			if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT) {

				// TODO Auto-generated method stub
				if(!END_TEXT_CHANGED_BY_SLIDER) {
					// Change slider
					try{
						int newValue = Integer.parseInt(edt_endTime.getText().toString());
						if (start_realPos<newValue && newValue > fileDuration) {
							edt_startTime.setText("" + end_realPos);
						} else {
							end_realPos = newValue;
							img_selection_end.scrollTo((int) -end_realPos  + slider.getIntrinsicWidth()/2, 0);
							drawSelectionRegion(start_realPos - graph_realPos, end_realPos - graph_realPos);
						}
						
					} catch (NumberFormatException e) {
						edt_endTime.setText("" + end_realPos);
					}
				} else {
					END_TEXT_CHANGED_BY_SLIDER = false;
				} 
				         
            }
            return false;

		}
	};
	
	private OnCheckedChangeListener alarmCheckedListener = new OnCheckedChangeListener() {
		
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			// TODO Auto-generated method stub
			cb_alarmDefault.setEnabled(isChecked);
			if (!isChecked) {
				cb_alarmDefault.setChecked(false);
			}
		}
	};
	private OnCheckedChangeListener ringtoneCheckedListener= new OnCheckedChangeListener() {
		
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			// TODO Auto-generated method stub
			cb_ringtoneDefault.setEnabled(isChecked);
			if (!isChecked) {
				cb_ringtoneDefault.setChecked(false);
			}
		}
	};
	
	private OnCheckedChangeListener notificationCheckedListener= new OnCheckedChangeListener() {
		
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			// TODO Auto-generated method stub
			cb_notificationDefault.setEnabled(isChecked);
			if (!isChecked) {
				cb_notificationDefault.setChecked(false);
			}
		}
	};
}
